package com.caldremch.rxretrofit.api;

import android.content.Context;

import com.caldremch.rxretrofit.api.function.MyFunction;
import com.caldremch.rxretrofit.api.listener.NextCallback;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import okhttp3.RequestBody;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by Caldremch on 2017-06-15 23:40
 */

public class ApiRetrofit extends BaseApiRetrofit{

    protected MyApi mApi;
    protected static ApiRetrofit mInstance;

    public ApiRetrofit() {
        super();
        Gson gson = new GsonBuilder()
                .setLenient()
                .create();

        //在构造方法中完成对Retrofit接口的初始化
        mApi = new Retrofit.Builder()
                .baseUrl(MyApi.BASE_URL)
                .client(getClient())
                .addConverterFactory(GsonConverterFactory.create(gson))
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build()
                .create(MyApi.class);
    }

    public static ApiRetrofit getInstance() {
        if (mInstance == null) {
            synchronized (ApiRetrofit.class) {
                if (mInstance == null) {
                    mInstance = new ApiRetrofit();
                }
            }
        }
        return mInstance;
    }

    /**
     * 获取请求体
     * @param obj
     * @return
     */
    private RequestBody getRequestBody(Object obj) {
        String route = new Gson().toJson(obj);
        RequestBody body=RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"),route);
        return body;
    }




    /**
     * 执行请求
     * @param context
     * @param observable
     * @param onResponseListener
     * @param <T>
     */
    public static <T> void doRequest(Context context,Observable observable,NextCallback<T> onResponseListener){


        MyObserver mo = new MyObserver<>(onResponseListener);
        MyFunction function = new MyFunction<>();
        observable
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .map(function)
                .subscribe(mo);


        //添加Disposable到baseActivity, 用于取消请求
        if (context instanceof BaseActiviy){
            BaseActiviy activiy = (BaseActiviy) context;
            activiy.addDisposable(mo.getDisposable());
        }


    }

}
